package io.renren.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @program: stf
 * @description: 文件工具类
 * @author: Custom
 * @create: 2018-11-04 22:04
 **/

public class UploadUtils {

    private static final String ROOTPATH = "D:/upload/img/";

    public static final int ICON = 0;
    public static final int USERIMG = 1;
    public static final int SLIDESHOW = 2;


    public static R uploadImage(MultipartFile[] myFileName,String urlPath,int type) throws IOException {
        //子目录
        String sonPath = "";
        //真是名称
        String realName = "";
        switch (type){
            case ICON:
                sonPath = "icon/";
                if(!createDir(ROOTPATH+sonPath)){
                    return R.error("上传失败！");
                }
                break;
            case SLIDESHOW:
                sonPath = "slideshow/";
                if(!createDir(ROOTPATH+sonPath)){
                    return R.error("上传失败！");
                }
                break;
            case USERIMG:
                sonPath = "project/";
                if(!createDir(ROOTPATH+sonPath)){
                    return R.error("上传失败！");
                }
                break;
            default:
                return R.error("上传类型标识错误！");
        }
        List<String> names = new ArrayList<>();
        if (myFileName != null) {

            //获取文件名称
            for (MultipartFile file : myFileName) {
                String fileName = file.getOriginalFilename();
                String fileNameExtension = fileName.substring(fileName.indexOf("."), fileName.length());
                // 生成实际存储的真实文件名
                realName = UUID.randomUUID().toString().replaceAll("-", "") + fileNameExtension;
                //创建保存的文件
                File uploadFile = new File(ROOTPATH + sonPath, realName);
                file.transferTo(uploadFile);
                names.add(urlPath + sonPath+realName);
            }
        }
//        String str = urlPath + sonPath + realName;
        return R.ok().put("data",names);
    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            System.out.println("创建目录" + destDirName + "失败，目标目录已经存在");
            return true;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            System.out.println("创建目录" + destDirName + "成功！");
            return true;
        } else {
            System.out.println("创建目录" + destDirName + "失败！");
            return false;
        }
    }

}
